package com.atung.tool;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.atung.response.ResponseGetAccessToken;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;

@Service
public class TemplateTool {


	
	@Value("${wx.appid}")
	private String appid;
	@Value("${wx.secret}")
	private String secret;
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	
	//发布订阅消息模板
	public String sendTemplateURL="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?";
	
	//获取access_token
	
	public static String getAccessTokenURL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%S&secret=%S";
	
	public  void sendPostTemplate(Map<String,String> tousers,String template_id) throws Exception{
		for(String touser:tousers.keySet()){
			Map<String,Object>param=new HashMap<String, Object>();
			param.put("access_token", getAccessToken());
			param.put("touser", touser);
			param.put("template_id", template_id);
			param.put("page", "index");
			param.put("miniprogram_state","developer");
			param.put("lang","zh_CN");
			Map<String,String> data=new HashMap<>();
			param.put("data", data.toString());
			HttpUtil.post(sendTemplateURL, param);
		}
		
	}
	
	public String getAccessToken() throws Exception{
//		System.out.println();
		if(!stringRedisTemplate.hasKey(Dictionaries.schoolAccessTokenRedisKey)){
			System.err.print("---------");
			return stringRedisTemplate.opsForValue().get(Dictionaries.schoolAccessTokenRedisKey);
		};
		String response=HttpUtil.get(String.format(getAccessTokenURL, appid,secret));
		ResponseGetAccessToken  AccessToken=JSONUtil.toBean(response, ResponseGetAccessToken.class);
		if(Objects.nonNull(AccessToken.getErrcode())){
			throw new Exception();
		}
		stringRedisTemplate.opsForValue().set(Dictionaries.schoolAccessTokenRedisKey, AccessToken.getAccess_token(),AccessToken.getExpires_in(), TimeUnit.MILLISECONDS);
		return AccessToken.getAccess_token();
	}
}
